package com.rcl.mvvmdemo.taobao

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.jetpacktaobao.domain.DataX
import com.example.jetpacktaobao.OnSellRepository
import com.example.jetpacktaobao.base.LoadState
import com.rcl.mvvmdemo.domain.OnSellData
import kotlinx.coroutines.launch

class OnSellViewModel : ViewModel() {

    val contentList = MutableLiveData<MutableList<DataX>>()
    val loadState = MutableLiveData<LoadState>()

    private val onSellRepository by lazy {
        OnSellRepository()
    }

    companion object {
        //默认第一页
        const val DEFAULT_PAGE = 1
    }

    //当前页
    private var mCurrentPage = DEFAULT_PAGE

    private var isLoaderMore = false

    /**
     * 加载更多内容
     */
    fun loadMore() {
        Log.i("aaaaa", "loadMore...")
        isLoaderMore = true
        loadState.value = LoadState.LOADER_MORE_LOADING
        //去加载更多内容
        mCurrentPage++
        loadHomeArticleByPage(mCurrentPage)
    }

    /**
     * 加载首页内容
     */
    fun loadContent() {
        this.listContentByPage(mCurrentPage)
    }

    private fun listContentByPage(page: Int) {
        viewModelScope.launch {
            val onSellList: OnSellData = onSellRepository.getOnSellList(page)
            Log.i(
                "aaaaa",
                "result size==>: ${onSellList.tbk_dg_optimus_material_response.result_list.map_data.size}"
            )
        }
    }

    /**
     * 首页文章列表
     */
    fun loadHomeArticleList() {
        isLoaderMore = false
        loadState.value = LoadState.LOADING
        loadHomeArticleByPage(mCurrentPage)
    }

    private fun loadHomeArticleByPage(page: Int) {
        viewModelScope.launch {
            try {
                val articleList = onSellRepository.getArticleList(page)
                //Log.i("aaaaa", "loadHomeArticleByPage result size==>: ${articleList.size}")
                val oldValue = contentList.value ?: mutableListOf()
                //这边直接就是主线程
                oldValue.addAll(articleList.datas)
                contentList.value = oldValue
                Log.i("aaaaa", "load success...")
                if (articleList.datas.isEmpty()) {
                    mCurrentPage--
                    loadState.value =
                        if (isLoaderMore) LoadState.LOADER_MORE_EMPTY else LoadState.EMPTY
                } else {
                    loadState.value = LoadState.SUCCESS
                }
            } catch (e: Exception) {
                mCurrentPage--
                if (e is NullPointerException) {
                    //没有更多内容的时候，会有一个空指针回来
                    loadState.value = LoadState.LOADER_MORE_EMPTY
                }
                e.printStackTrace()
                loadState.value = if (isLoaderMore) LoadState.LOADER_MORE_ERROR else LoadState.ERROR
            }

        }
    }
}